import datetime
import logging
import os
import time
import wsgiref.handlers
import random

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import simplejson as JSON

import py.datamodel

class Owner(webapp.RequestHandler):
    def get(self):
        self.post()
        
    def post(self):
        self.response.headers['Content-Type'] = 'text/html'
       
        sos_identifier = self.request.cookies.get("sos_identifier")
        if not sos_identifier:
            sos_identifier = str(random.random()) + str(random.random())
        
        self.response.headers.add_header("Set-Cookie", "sos_identifier=" + str(sos_identifier))
        
        owner = self.request.get("owner")
        owner = JSON.loads(owner)["id"]
        container = "orkut"
        ownerId = container + "-" + owner;

        preferences = db.GqlQuery("SELECT * FROM Preferences WHERE owner = :1", ownerId)
        sosPrefs = db.GqlQuery("SELECT * FROM Preferences WHERE owner = :1", "sneakoscope")

        knownRecords = db.GqlQuery("SELECT * FROM Visit where ownerId = :1 order by enterTime DESC LIMIT 100", ownerId)
        unknownRecords = db.GqlQuery("SELECT * FROM UnknownVisit where ownerId = :1 order by enterTime DESC LIMIT 100", ownerId)

        if  knownRecords.count() == 0 and unknownRecords.count() == 0:
            self.redirect("/html/novisits.html")
        else:
            template_values = {}
            template_values["userData"] = self.request.get("data")
            template_values["container"] = container
            
            template_values["sosTotal"] = sosPrefs.get().totalCount
            template_values["sosPrefs"] = sosPrefs.get().counters
            template_values['userTotal'] = preferences.get().totalCount
            template_values['userPrefs'] = preferences.get().counters
            
            template_values['ownerId'] = ownerId        
            template_values['knownRecords'] = knownRecords
            template_values['unknownRecords'] = unknownRecords
            
            if self.request.get("view") == "canvas":
                path = os.path.join(os.path.dirname(__file__), '../templates/owner-canvas.html')
            else:
                path = os.path.join(os.path.dirname(__file__), '../templates/owner-profile.html')
            path = os.path.abspath(path);
            self.response.out.write(template.render(path, template_values))
        
if __name__ == '__main__':
  application = webapp.WSGIApplication(
      [
        ('/.*', Owner)
      ],
      debug=True)

  wsgiref.handlers.CGIHandler().run(application)
